import React from 'react';
import _ from 'lodash';
import PropTypes from 'prop-types';
import { Icon } from '@iconify/react';
import searchFill from '@iconify/icons-eva/search-fill';
import trash2Fill from '@iconify/icons-eva/trash-2-fill';
import roundFilterList from '@iconify/icons-ic/round-filter-list';
import settingsOutline from '@iconify/icons-eva/settings-outline';
import cloudDownloadOutline from "@iconify/icons-eva/cloud-download-outline";

// material
import { styled } from '@mui/material/styles';
import {
  Box,
  Toolbar,
  Tooltip,
  FormControl,
  IconButton,
  FormLabel,
  FormControlLabel,
  FormGroup,
  Checkbox,
  OutlinedInput,
  InputAdornment,
  Typography,
  Popover, InputLabel, Select, MenuItem, Button
} from '@mui/material';

import { ExportToExcel } from '../../@common/AsyncExportExcel/AsyncExcel';

// ----------------------------------------------------------------------

const RootStyle = styled(Toolbar)(({ theme }) => ({
  height: 96,
  display: 'flex',
  justifyContent: 'space-between',
  padding: theme.spacing(0, 1, 0, 3)
}));

const SearchStyle = styled(OutlinedInput)(({ theme }) => ({
  width: 240,
  transition: theme.transitions.create(['box-shadow', 'width'], {
    easing: theme.transitions.easing.easeInOut,
    duration: theme.transitions.duration.shorter
  }),
  '&.Mui-focused': { width: 320, boxShadow: theme.customShadows.z8 },
  '& fieldset': {
    borderWidth: `1px !important`,
    borderColor: `${theme.palette.grey[500_32]} !important`
  }
}));

// ----------------------------------------------------------------------

UserListToolbar.propTypes = {
  headLabel: PropTypes.array,
  excelData: PropTypes.array,
  numSelected: PropTypes.number,
  filterName: PropTypes.string,
  onFilterName: PropTypes.func,
  onChangeDisplayColums: PropTypes.func
};

export default function UserListToolbar({ headLabel, excelData, numSelected, filterName, filterGender, onFilterByName, onFilterByGender, onChangeDisplayColums, onBatchDelete }) {

  const [displayEl, setDisplayEl] = React.useState(null);

  const handleClick = (event) => {
    setDisplayEl(event.currentTarget);
  };

  const handleClose = () => {
    setDisplayEl(null);
  };

  const open = Boolean(displayEl);
  const id = open ? 'simple-popover' : undefined;


  /**/
  const [selectedColums, setSelectedColums] = React.useState(()=>{
    return _.map(headLabel, colum=>colum.id)
  });

  const handleChangeDisplayColums = ({ target: { value, checked } }, { isDisplay }) => {
    if(checked){
      setSelectedColums([...selectedColums, value]);
      return;
    }
    setSelectedColums([...selectedColums.map(colum=>colum.id !== value)]);
  };

  return (
    <RootStyle
      sx={{
        ...(numSelected > 0 && {
          color: 'primary.main',
          bgcolor: 'primary.lighter'
        })
      }}
    >
      {numSelected > 0 ? (
        <Typography component="div" variant="subtitle1">
          {numSelected} selected
        </Typography>
      ) : (
          <Box sx={{ minWidth: '50%' }}>
            <SearchStyle
                value={filterName}
                onChange={onFilterByName}
                placeholder="Search user..."
                startAdornment={
                  <InputAdornment position="start">
                    <Box component={Icon} icon={searchFill} sx={{ color: 'text.disabled' }} />
                  </InputAdornment>
                }
            />
            <FormControl sx={{ width: '8rem', marginLeft: '1rem' }}>
              <InputLabel id="demo-simple-select-label">Gender</InputLabel>
              <Select
                  labelId="demo-simple-select-label"
                  id="demo-simple-select"
                  value={filterGender}
                  label="Gender"
                  onChange={onFilterByGender}
              >
                <MenuItem value={`0`}>Male</MenuItem>
                <MenuItem value={`1`}>Female</MenuItem>
                <MenuItem value={`2`}>保密</MenuItem>
              </Select>
            </FormControl>

            <FormControl sx={{ display: 'contents' }}>
              <Button
                sx={{ marginLeft: '0.8rem' }}
                variant="contained"
                color="primary"
              >
                Search
              </Button>

              <Button
                sx={{ marginLeft: '0.8rem' }}
                variant="contained"
                color="primary"
              >
                Reset
              </Button>
            </FormControl>
          </Box>
      )}

      {numSelected > 0 ? (
        <Tooltip title="Delete">
          <IconButton onClick={onBatchDelete}>
            <Icon icon={trash2Fill} />
          </IconButton>
        </Tooltip>
      ) : (
        <div>
          <>
            <ExportToExcel
                dataSource={excelData}
                fileName={`数据源${(new Date()).getTime()}`}
            >
              <IconButton>
                <Icon icon={cloudDownloadOutline} />
              </IconButton>
            </ExportToExcel>

            <Tooltip title="Display column">
              <IconButton aria-describedby={id} onClick={handleClick}>
                <Icon icon={settingsOutline} />
              </IconButton>
            </Tooltip>
            <Popover
                id={id}
                open={open}
                anchorEl={displayEl}
                onClose={handleClose}
                anchorOrigin={{
                  vertical: 'bottom',
                  horizontal: 'left',
                }}
            >
              <Box sx={{ display: 'flex' }}>
                <FormControl sx={{ m: 3 }} component="fieldset" variant="standard">
                  <FormLabel component="legend">Show Columns</FormLabel>
                  <FormGroup>
                    {
                      _.map(headLabel, headCell=>(
                        <FormControlLabel
                          key={headCell.id}
                          control={
                            <Checkbox checked={headCell.isDisplay} value={headCell.id} onChange={(event)=>onChangeDisplayColums(event, headCell)} />
                          }
                          label={headCell.label}
                        />
                      ))
                    }
                  </FormGroup>
                </FormControl>
              </Box>
            </Popover>
          </>

          <Tooltip title="Filter list">
            <IconButton>
              <Icon icon={roundFilterList} />
            </IconButton>
          </Tooltip>
        </div>
      )}
    </RootStyle>
  );
}
